<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">
          <template>
            <a-col :md="4" :sm="8">
              <a-form-item label="车辆类型名称">
                <a-input placeholder="请输入车辆类型名称" v-model="queryParam.carTypeName"></a-input>
              </a-form-item>
            </a-col>

            <a-col :md="4" :sm="8">
              <a-form-item label="车辆类型">
                <a-select v-model="queryParam.carType" placeholder="请输入车辆类型">
                  <a-select-option :value="''">请选择车辆类型</a-select-option>
                  <a-select-option :value="0">临时车</a-select-option>
                  <a-select-option :value="1">月租车</a-select-option>
                  <a-select-option :value="2">储值车</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="2" :sm="4" v-has="'admin:parkCode'">
            <a-form-item>
              <a-date-picker placeholder="开始日期" @change="onChangeStartTime"/>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="4" v-has="'admin:parkCode'">
            <a-form-item>
              <a-date-picker placeholder="结束日期" @change="onChangeEndTime"/>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-upload
          name="file"
          :showUploadList="false"
          :multiple="false"
          :headers="UploadHeader"
          :action="uploadUrl"
          @change="handleImportExcel"
          accept=".xls,.xlsx">
       <a-button :disabled="loading" type="primary" icon="import">导入</a-button>
      </a-upload>
    </div>
    <!-- table区域-begin -->
    <div>
      <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :data-source="dataSource"
          :pagination="ipagination"
          :loading="loading"
          @change="handleTableChange">
        <span slot="carTypeName" slot-scope="text,record" @dblclick="handleEdit(record)">
          <a-input
              v-if="record.editable"
              v-model="text"
              @input="carTypeNameInput(text,record)"
              size="small"
          />
          <template v-else>
            {{ text }}
          </template>
        </span>
        <span @dblclick="handleEdit(record)" slot="isOpen" slot-scope="text,record">
          <a-select
              v-if="record.editable"
              v-model="text"
              :options="isOpenoptions"
              @select="IsOpenSelect(text,record)"
              size="small"
              style="width: 70%">
          </a-select>
          <template v-else>
            {{ text }}
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)" v-if="record.editable === false">编辑</a>
          <div v-else>
            <a @click="handleSave(record)">保存</a>
            <a-divider type="vertical"></a-divider>
            <a @click="handleCancel(record)">取消</a>
          </div>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <configCarType-modal ref="modalForm" @ok="modalFormOk"></configCarType-modal>
  </a-card>
</template>

<script>
import ConfigCarTypeModal from './modules/ConfigCarTypeModal'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {deleteAction, getAction, downFile, httpAction} from '@/api/manage'
import {filterObj} from '@/utils/util';
import Vue from "vue";
import {ACCESS_TOKEN} from "@/store/mutation-types";
import {axios} from "@/utils/request"

export default {
  name: "ConfigCarTypeList",
  mixins: [JeecgListMixin],
  components: {
    ConfigCarTypeModal,
  },
  data() {
    return {
      uploadUrl: axios.defaults.baseURL + "/ConfigCarType/configCarType/importExcel",
      description: '车辆类型管理管理页面',
      isOpenoptions: [{label: '启用', value: '启用'}, {label: '不启用', value: '不启用'}]
      ,
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          height: 30,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '停车场编号',
          align: "center",
          dataIndex: 'parkCode',
        },
        {
          title: '停车场名称',
          align: "center",
          dataIndex: 'parkName'
        },
        {
          title: '车辆类型名称',
          align: "center",
          width: 140,
          dataIndex: 'carTypeName',
          scopedSlots: {customRender: 'carTypeName'}
        },
        // {
        //   title: '默认名称',
        //   align: "center",
        //   dataIndex: 'defaultName'
        // },
        {
          title: '车辆类型',
          align: "center",
          dataIndex: 'carType',
          customRender: function (t, r, index) {
            if (t == 0) {
              return "临时车"
            } else if (t == 1) {
              return "月租车"
            } else if (t == 2) {
              return "储值车"
            }
          }
        },
        {
          title: '是否启用',
          align: "center",
          dataIndex: 'isOpen',
          width: 140,
          scopedSlots: {customRender: 'isOpen'}
        },
        {
          title: '创建时间',
          align: "center",
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          width: 140,
          scopedSlots: {customRender: 'action'},
        }
      ],
      url: {
        edit: "/ConfigCarType/configCarType//edit",
        list: "/ConfigCarType/configCarType/list",
        delete: "/ConfigCarType/configCarType/delete",
        deleteBatch: "/ConfigCarType/configCarType/deleteBatch",
        exportXlsUrl: "/ConfigCarType/configCarType/exportXls",
        importExcelUrl: "/ConfigCarType/configCarType/importExcel",
      },
      queryParam: {
        "startTime": "",
        "endTime": "",
        "type": "-1",
        "carType": "",
      },
      isorder: {
        column: 'createTime',
        order: 'desc'
      },
      carTypeNameInputValue: '',
      IsOpenSelectValue: '',
      EditForm: {},
      ImportData: {},
      TableEditing: false,
      UploadHeader: {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)}
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  created() {
    this.keyupEnter()
  },
  methods: {

    handleEdit(record) {
      if (this.TableEditing === false) {
        record.editable = true
        this.TableEditing = true
      }
    },
    handleSave(record) {
      this.loading = true
      const that = this
      record.editable = false
      this.TableEditing = false
      if (!this.url.edit) {
        console.log("请配置编辑路径")
      } else {
        let Params = Object.assign(this.EditForm, record)

        if (Params.isOpen === "不启用") {
          Params.isOpen = '0'
        } else {
          Params.isOpen = '1'
        }
        httpAction(this.url.edit, Params, "put").then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.$emit('ok');
          } else {
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.loadData()
          that.confirmLoading = false;
        })
      }
    },
    handleCancel(record) {
      record.editable = false
      this.TableEditing = false
    },

    onChangeStartTime(date, dateString) {
      this.queryParam.startTime = dateString;
    },
    onChangeEndTime(date, dateString) {
      this.queryParam.endTime = dateString;
    },
    searchQuery() {
      let startTime = this.queryParam.startTime;
      let endTime = this.queryParam.endTime;
      if (startTime !== "" && endTime !== "") {
        if (startTime > endTime) {
          this.$message.error("开始时间不能大于结束时间");
          return
        }
      }
      if (startTime === "" && endTime !== "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime !== "" && endTime === "") {
        this.$message.error("请选择结束时间");
        return
      }
      this.loadData(1);
    },
    getQueryParams() {
      var param = Object.assign({}, this.isorder, this.queryParam);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      param.parkCode = this.parkCode;
      if (this.queryParam.startTime !== "" && this.queryParam.endTime !== "") {
        param.startTime = this.queryParam.startTime + " 00:00:00";
        param.endTime = this.queryParam.endTime + " 23:59:59";
      }
      return filterObj(param);
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      let params = this.getQueryParams();
      if (this.parkCode == "") {
        params.parkCode = null;
      }
      this.loading = true;
      getAction(this.url.list, params).then((res) => {

        if (res.success) {
          this.dataSource = res.result.records;
          this.dataSource.forEach((data) => {
            if (data.isOpen === "0") {
              data.isOpen = "不启用"
            } else {
              data.isOpen = "启用"
            }
            this.$set(data, 'editable', false)
          })
          this.ipagination.total = res.result.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false;
      })
    },
    batchDel: function () {

      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = "";
        for (var a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].id + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            });
          }
        });
      }
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, {id: id}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    IsOpenSelect(text, record) {

      record.isOpen = text

    },
    carTypeNameInput(text, record) {

      record.carTypeName = text

    },
    keyupEnter() {
      document.onkeydown = e => {
        let body = document.getElementsByTagName('body')[0]
        if (e.keyCode === 13) {
          this.loadData(1);
        }
      }
    },
    handleImportExcel(info) {
      if (info.file.status === 'done') {
        console.log(info);
        let response = info.file.response
        if (response.success || response.code === 200) {
          this.$message.success(`${info.file.name} 文件上传成功`);
          this.loadData();
        }
        if (response.code === 500) {
          this.$message.error(info.file.response.message);
        }
        if (info.file.response.code === 201) {
          let {
            message,
            result: {
              msg,
              fileUrl,
              fileName
            }
          } = info.file.response
          let href = window._CONFIG['domianURL'] + fileUrl
          this.$warning({
            title: message,
            content: (
                <div>
                  <span>{msg}</span><br/>
                  <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
                </div>
            )
          })
        }
      }
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
